package com.outfood.intercept;

import com.outfood.common.common.CurrentUser;
import com.ruoyi.common.exception.BusinessException;
import com.rys.common.utils.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author huisonglin
 * @Description
 * @PackageName intelligent-vehicle-platform
 * @Package com.intelligent.intercept
 * @Date 2023/7/20 16:38
 * @Version 1.0
 */
@Component
public class LoginIntercept implements HandlerInterceptor {
    
    public static String TOKEN="token";



    @Resource
    RedisTemplate redisTemplate;

    public static String LOGINEDUSER="LoginedUser:";
    

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{

        String token = request.getHeader(TOKEN);
        if(StringUtils.isBlank(token)){
            request.getAttribute(TOKEN);
        }
        if(StringUtils.isBlank(token)){
            throw new BusinessException("未授权");
        }
        Object o = redisTemplate.opsForValue().get(LOGINEDUSER + token);
        if(o == null){
            throw new BusinessException("登录过期，请重新打开小程序");
        }
        CurrentUser.setUserId(Long.valueOf(o.toString()));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUser.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
